<template>
<div>
  <el-upload
    action="https://jsonplaceholder.typicode.com/posts/"
    :on-remove="handleRemove"
    :before-remove="beforeRemove"
    :show-file-list="false"
    :before-upload="uploadBefore"
    :http-request="handUpload"
  >
    <el-button size="small" type="warning">点击上传</el-button>
    <div slot="tip" class="el-upload__tip"><label :class="descClass">{{ desc }}</label></div>
  </el-upload>
  <div v-if=" uploadFileName !='' ">
      <a :href="uploadUrl" target="_blank" >{{ uploadFileName }} </a>
      <el-button @click="delFile" style="padding:2px" circle size="mini" type="primary" icon="el-icon-close"></el-button>
  </div>
</div>
</template>

<script>
import OSS from 'ali-oss'
import report from "../../apiUrl/reportApi";
import config from '@/config'
// import moment from 'moment'

export default {
  name: "reportFileUpload",
  props: {
    desc: '',
    uploadPath: '',
    descClass:'',
    accept: {
      type: String,
      default:
        "image/*, .rar, .zip,.doc, .docx, .pdf, .jpg, .png, .jpeg, .xlsx,.txt,.xlm, .xls"
    }
  }, //["desc","uploadPath","acceptType"],
  data() {
    return {
        uploadUrl: '',
        uploadFileName: '',
        client: {},
        OSSurl: `${config.upUrl}/report`
    };
  },
  methods: {
    handleRemove(file, fileList) {},
    beforeRemove(file, fileList) {},
    uploadBefore(file){
        if(file.name.indexOf("+")>0){
            this.$message.error("文件名不能包含'+'号");
            return false;
        }
        let type = file.name
        .split(".")
        [file.name.split(".").length - 1].toLowerCase();
        if (this.accept.includes(type)) {
            return true;
        } else {
            this.$message({
            showClose: true,
            message: "文件类型不匹配",
            type: "error"
            });
            return false;
        }
    },
    async handUpload(option) {
        const loading = this.$loading({
            text: "文件上传中,请稍候...",
            target: ".whole-process-container"
        })
        await report.getStsPolicy().then(rs => {
            this.client = rs.data
        })
        let client = new OSS({
            accessKeyId: this.client.AccessKeyId,
            accessKeySecret: this.client.AccessKeySecret,
            stsToken: this.client.SecurityToken,
            //endpoint: 'oss-cn-beijing',
            bucket: this.client.bucket,
            region: 'oss-cn-beijing'
        })
        
        let file = option.file
        let date = this.$formatYMD(new Date(),"-");
        
        // this.spotInfo.provinceId+"/"+ this.spotInfo.cityId+"/"+ this.spotInfo.areaId+"/" + 
        let resource = this.OSSurl +"/"+ date + "/" +file.name
        console.log(resource)
        // 分片上传文件
        let ret = await client.multipartUpload(resource, file, {
            progress: async function (p) {
            let e = {}
            e.percent = p * 100
            option.onProgress(e)
            }
        })
        loading.close();
        if (ret.res.statusCode === 200) {
            let _url = ret.res.requestUrls[0]
            if(_url.indexOf("?")>0){
                _url = _url.substr(0,_url.indexOf("?"))
            }
            this.uploadUrl = decodeURIComponent(_url)
            this.uploadFileName = file.name
            this.$message.success('上传成功')
        } else {
            option.onError('上传失败')
            this.$message.error('上传失败,请重新尝试')
        }
    },
    delFile(){
        this.uploadFileName = ""
        this.uploadUrl = ""
    },
  },
  watch: {
      uploadUrl(val) {
        this.$emit('update:uploadPath',val);
      },
      uploadPath(val) {
          if(val){
            this.uploadUrl = val
            this.uploadFileName = val.substr(val.lastIndexOf("/")+1)
          }else {
            this.uploadUrl = ''
            this.uploadFileName = ''
          }
      }
  }
};
</script>

